<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="量化投资,强化学习,人工智能,AI," />










<meta name="description" content="我没偏题，这还是量化交易的内容。交易不就是人跟人(或人背后的代码)在博弈嘛。初步想法是先把框架搭起来，包括下棋规则，判断输赢什么的，然后用传统的人工智能方法实现人机对战，最后试试AlphaGo的强化学习。找了一些网站，这有个现成的，我就先抄再研究改进了。特此感谢！首先先实现棋盘类，实现下棋的规则及输赢判断。最后用这个类实现人与人的对战。这一段基本是抄人家的程序再改改，因为没有ai，就略过了。 ok">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记102——用电脑下五子棋">
<meta property="og:url" content="https://zwdnet.github.io/2021/03/13/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0102%E2%80%94%E2%80%94%E7%94%A8%E7%94%B5%E8%84%91%E4%B8%8B%E4%BA%94%E5%AD%90%E6%A3%8B/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="我没偏题，这还是量化交易的内容。交易不就是人跟人(或人背后的代码)在博弈嘛。初步想法是先把框架搭起来，包括下棋规则，判断输赢什么的，然后用传统的人工智能方法实现人机对战，最后试试AlphaGo的强化学习。找了一些网站，这有个现成的，我就先抄再研究改进了。特此感谢！首先先实现棋盘类，实现下棋的规则及输赢判断。最后用这个类实现人与人的对战。这一段基本是抄人家的程序再改改，因为没有ai，就略过了。 ok">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/01.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/02.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/03.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/04.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/05.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/06.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/07.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/08.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/09.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/10.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/11.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/12.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/13.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/14.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/15.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/16.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/17.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/18.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/19.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/20.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/21.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2021-03-13T21:08:13.000Z">
<meta property="article:modified_time" content="2021-03-14T05:33:08.460Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="强化学习">
<meta property="article:tag" content="人工智能">
<meta property="article:tag" content="AI">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/01.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2021/03/13/量化投资学习笔记102——用电脑下五子棋/"/>





  <title>量化投资学习笔记102——用电脑下五子棋 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2021/03/13/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0102%E2%80%94%E2%80%94%E7%94%A8%E7%94%B5%E8%84%91%E4%B8%8B%E4%BA%94%E5%AD%90%E6%A3%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记102——用电脑下五子棋</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-03-13T21:08:13+00:00">
                2021-03-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  6.3k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  23
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>我没偏题，这还是量化交易的内容。交易不就是人跟人(或人背后的代码)在博弈嘛。初步想法是先把框架搭起来，包括下棋规则，判断输赢什么的，然后用传统的人工智能方法实现人机对战，最后试试AlphaGo的强化学习。<br>找了一些网站，这有个<a target="_blank" rel="noopener" href="http://www.skywind.me/blog/archives/1029">现成的</a>，我就先抄再研究改进了。特此感谢！<br>首先先实现棋盘类，实现下棋的规则及输赢判断。最后用这个类实现人与人的对战。这一段基本是抄人家的程序再改改，因为没有ai，就略过了。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/01.jpg"></p>
<p>ok，下棋，判断输赢都没问题了。下面来给程序增加“人工智能”。先用最简单的方法——随机乱下。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 随机算法确定下棋位置</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">randomPut</span>(<span class="params">board, who</span>):</span></span><br><span class="line">    random.seed(time.time())</span><br><span class="line">    <span class="keyword">if</span> board.full():</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        i = random.randint(<span class="number">0</span>, <span class="number">14</span>)</span><br><span class="line">        j = random.randint(<span class="number">0</span>, <span class="number">14</span>)</span><br><span class="line">        <span class="keyword">if</span> board[i][j] == <span class="number">0</span>:</span><br><span class="line">            board.put(i, j, who)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/02.jpg"><br>就是这样，计算机完全随机下棋，想赢很容易，想输却很难。我想把棋盘下满，测试一下棋盘下满的情况，但却都在无意当中就赢了。<br>下面改进一下:五子棋往往落子的地方是在对方上一次落子的区域附近。就设定在对方上次落子位置为中心的5×5大小的区域内，最多有24个位置可以随机选择。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 改进随机算法，在对方上次落子位置附近5×5的范围内随机落子</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">nearRandomPut</span>(<span class="params">board, who</span>):</span></span><br><span class="line">    random.seed(time.time())</span><br><span class="line">    <span class="keyword">if</span> board.full():</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">    last = board.getLast()</span><br><span class="line">    <span class="keyword">if</span> last == [-<span class="number">1</span>, -<span class="number">1</span>]:</span><br><span class="line">        x = <span class="number">7</span></span><br><span class="line">        y = <span class="number">7</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        x = last[<span class="number">0</span>]</span><br><span class="line">        y = last[<span class="number">1</span>]</span><br><span class="line">    count = <span class="number">0</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        count += <span class="number">1</span></span><br><span class="line">        <span class="comment">#  防止所有附近区域都下满的情况</span></span><br><span class="line">        <span class="keyword">if</span> count &gt;= <span class="number">100</span>:</span><br><span class="line">            i = random.randint(<span class="number">0</span>, <span class="number">14</span>)</span><br><span class="line">            j = random.randint(<span class="number">0</span>, <span class="number">14</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            i = random.randint(<span class="built_in">max</span>(x-<span class="number">2</span>, <span class="number">0</span>), <span class="built_in">min</span>(x+<span class="number">2</span>, <span class="number">14</span>))</span><br><span class="line">            j = random.randint(<span class="built_in">max</span>(y-<span class="number">2</span>, <span class="number">0</span>), <span class="built_in">min</span>(y+<span class="number">2</span>, <span class="number">14</span>))</span><br><span class="line">        <span class="keyword">if</span> board[i][j] == <span class="number">0</span>:</span><br><span class="line">            board.put(i, j, who)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<p>现在程序就变得有智能多了<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/03.jpg"></p>
<p>但是程序还是不知道封堵对方已经有三个棋子连线的位置。<br>再继续改进算法之前，先对程序进行重构吧。无论人下棋还是电脑下棋，程序的结构都是基本一致的，能不能把它们的共同部分提炼出来，以后更改下棋算法的时候直接往里面塞不同的算法就行了?<br>写了一个contest函数，传入两个不同的算法函数，就可以用这两个算法进行对弈。考虑到先手有优势，随机决定哪个算法先手。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 算法与算法(包括人)之间对弈的一般过程</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">contest</span>(<span class="params">method1, method2, show = <span class="literal">True</span></span>):</span></span><br><span class="line">    random.seed(time.time())</span><br><span class="line">    methods = [method1, method2]</span><br><span class="line">    b = chessboard()</span><br><span class="line">    b.reset()</span><br><span class="line">    <span class="keyword">if</span> show:</span><br><span class="line">        display(b)</span><br><span class="line">    first = random.randint(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">    <span class="keyword">if</span> first == <span class="number">1</span>:</span><br><span class="line">        second = <span class="number">2</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        second = <span class="number">1</span></span><br><span class="line">    <span class="comment"># 游戏循环</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            <span class="keyword">if</span> methods[first-<span class="number">1</span>](b, first) == <span class="literal">True</span>:</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">        <span class="keyword">if</span> show:</span><br><span class="line">            display(b)</span><br><span class="line">        <span class="keyword">if</span> b.check() == first:</span><br><span class="line">            <span class="keyword">return</span> first</span><br><span class="line">        <span class="keyword">if</span> methods[second -<span class="number">1</span>](b, second) == <span class="literal">False</span>:</span><br><span class="line">            print(<span class="string">&quot;无法落子，游戏结束!&quot;</span>)</span><br><span class="line">            <span class="built_in">input</span>(<span class="string">&quot;按任意键继续&quot;</span>)</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> b.check() == second:</span><br><span class="line">            <span class="keyword">if</span> show:</span><br><span class="line">                display(b)</span><br><span class="line">            <span class="keyword">return</span> second</span><br><span class="line">        <span class="keyword">if</span> show:</span><br><span class="line">            display(b)</span><br><span class="line">       </span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>返回赢家的代号。再比较一下两种随机算法的获胜概率:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 比较两种随机算法</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">compareRandom</span>():</span></span><br><span class="line">    win = [<span class="number">0</span>, <span class="number">0</span>]</span><br><span class="line">    b = chessboard()</span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        epochs = <span class="built_in">input</span>(<span class="string">&quot;请输入对弈次数:&quot;</span>)</span><br><span class="line">        <span class="keyword">if</span> epochs.isdigit() <span class="keyword">and</span> <span class="built_in">int</span>(epochs) &gt; <span class="number">0</span>:</span><br><span class="line">            epochs = <span class="built_in">int</span>(epochs)</span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(epochs):</span><br><span class="line">        b.reset()</span><br><span class="line">        result = contest(randomPut, nearRandomPut)</span><br><span class="line">        win[result-<span class="number">1</span>] += <span class="number">1</span></span><br><span class="line">        print(<span class="string">&quot;第%d次对弈，%d取胜&quot;</span> % (i, result))</span><br><span class="line">        </span><br><span class="line">    winrate = [win[<span class="number">0</span>]/epochs, win[<span class="number">1</span>]/epochs]</span><br><span class="line">    print(<span class="string">&quot;获胜概率:&quot;</span>, winrate)</span><br><span class="line">    <span class="built_in">input</span>(<span class="string">&quot;按任意键继续&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>开启输出棋盘，大概一秒钟对弈几次，可以看到还是很激烈的。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/04.jpg"><br>把显示棋盘关了，多对弈几次看看。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/05.jpg"></p>
<p>可以看到优化前后的随机算法的胜率比为46.5:53.5，优化后要好一点。<br>现在研究的工具基本都有了，可以开始正儿八经的研究下棋算法了。<br>先考虑深度学习之前的算法，找到一本很老的书:《pc游戏编程:人机博弈》，王小春著。用的编程语言是C++。<br>1.棋盘的表示:用二维数组。<br>2.走法的产生:所有空白区域都可以落子。产生走法的方式有一次性全部产生和逐渐产生两种。<br>3.基本搜索技术:<br>①博弈树:根节点为开局，其子节点为甲的走法，这些节点每个子节点又对应乙的走法。叶子节点是棋局的结局。博弈树即包含所有对弈过程的搜索树。<br>②极大极小值算法:(Minimax Algorithm)令甲胜为1， 乙胜为-1，和局为0。所以甲选子节点值最大的走法，乙选子节点值最小的走法。对于子节点，甲走时选所有子节点中值最大的，乙选值最小的。其深度为固定的搜索树，其值由评分函数给出。启发式搜索。<br>③深度优先搜索。<br>④负极大值算法:父结点的值是各子节点值的负数的极大值。<br>4.估值: 对棋盘上每个子赋予一个估值，一方的棋盘估值就是其所有子的估值总和。评估棋子的灵活性，将该棋子所有可能的走法的估值总和。棋子之间的关系也会影响评估。双方估值之差为棋局局面的估值。<br>上述过程太耗时了，改进措施为:<br>①Alpha_Beta搜索:搜索到一定节点发现无需再进一步搜索时将相应的节点剪枝。<br>②渴望搜索(Aspiration Search):<br>③极小窗口搜索(Minimal Window Search)<br>书中最后有个五子棋的程序，可惜是用C++写的，还是用MFC。我找个python写的来参考一下吧。<br>几乎完全照搬<a target="_blank" rel="noopener" href="https://github.com/skywind3000/gobang/gobang.py">这里</a>上的代码，只是ta是用python2，我给改成python3，调通了。仅仅用了一层搜索，我已经很难赢程序了。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/06.jpg"></p>
<p>再跟之前的随机算法PK一下<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/07.jpg"></p>
<p>博弈树算法是碾压式的优势。<br>程序能跑不是目的，关键是学习。接下来我打算详细研究一下人家的代码。<br>在这个时候发现一个非常详细的<a target="_blank" rel="noopener" href="https://github.com/lihongxun945/myblog/labels/%E4%BA%94%E5%AD%90%E6%A3%8BAI%E6%95%99%E7%A8%8B%E7%AC%AC%E4%BA%8C%E7%89%88">教程</a> 参考一下吧。<br>现在顺着流程来理一下，首先是博弈树算法下一步棋的过程:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 博弈树算法下棋过程</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">treePut</span>(<span class="params">board, who</span>):</span></span><br><span class="line">    <span class="comment"># 如果是先手，随机下一个地方</span></span><br><span class="line">    last = board.getLast()</span><br><span class="line">    <span class="keyword">if</span> last == [-<span class="number">1</span>, -<span class="number">1</span>]:</span><br><span class="line">        row = random.randint(<span class="number">0</span>, <span class="number">14</span>)</span><br><span class="line">        col = random.randint(<span class="number">0</span>, <span class="number">14</span>)</span><br><span class="line">        <span class="keyword">if</span> board[row][col] == <span class="number">0</span>:</span><br><span class="line">            board.put(row, col, who)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">    s = searcher()</span><br><span class="line">    s.board = board</span><br><span class="line">   </span><br><span class="line">    <span class="comment"># 设置难度</span></span><br><span class="line">    DEPTH = <span class="number">1</span></span><br><span class="line">    score, row, col = s.search(who, DEPTH)</span><br><span class="line">    <span class="keyword">if</span> board[row][col] == <span class="number">0</span>:</span><br><span class="line">        board.put(row, col, who)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<p>核心代码，先设置遍历深度，然后调用搜索树的搜索方法，根据当前棋盘局面找到下一步的走法:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">score, row, col = s.search(who, DEPTH)</span><br></pre></td></tr></table></figure>
<p>具体搜索过程为:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">search</span>(<span class="params">self, turn, depth = <span class="number">3</span></span>):</span></span><br><span class="line">        self.maxdepth = depth</span><br><span class="line">        self.bestmove = <span class="literal">None</span></span><br><span class="line">        score = self.__search(turn, depth)</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">abs</span>(score) &gt; <span class="number">8000</span>:</span><br><span class="line">            self.maxdepth = depth</span><br><span class="line">            score = self.__search(turn, <span class="number">1</span>)</span><br><span class="line">        row, col = self.bestmove</span><br><span class="line">        <span class="keyword">return</span> score, row, col</span><br></pre></td></tr></table></figure>
<p>先设定最大搜索深度，然后调用具体执行搜索的函数__search(turn, depth)得到棋局评分，在这个函数里应该也设置了bestmove，即最佳落子位置。<br>现在来看具体执行搜索的步骤:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 递归搜索，返回最佳分数</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__search</span>(<span class="params">self, turn, depth, alpha = -<span class="number">0x7fffffff</span>, beta = <span class="number">0x7fffffff</span></span>):</span></span><br><span class="line">        <span class="comment"># 深度为零，评估棋盘并返回</span></span><br><span class="line">        <span class="keyword">if</span> depth &lt;= <span class="number">0</span>:</span><br><span class="line">            score = self.evaluator.evaluate(self.board, turn)</span><br><span class="line">            <span class="keyword">return</span> score</span><br><span class="line">           </span><br><span class="line">        <span class="comment"># 游戏结束，立马返回</span></span><br><span class="line">        score = self.evaluator.evaluate(self.board, turn)</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">abs</span>(score) &gt;= <span class="number">9999</span> <span class="keyword">and</span> depth &lt; self.maxdepth:</span><br><span class="line">            <span class="keyword">return</span> score</span><br><span class="line">           </span><br><span class="line">        <span class="comment"># 产生新的走法</span></span><br><span class="line">        moves = self.genmove(turn)</span><br><span class="line">        bestmove = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">        <span class="comment"># 枚举当前所有走法</span></span><br><span class="line">        <span class="keyword">for</span> score, row, col <span class="keyword">in</span> moves:</span><br><span class="line">            <span class="comment"># 标记当前走法到棋盘</span></span><br><span class="line">            self.board[row][col] = turn</span><br><span class="line">            <span class="comment"># 计算下一回合该谁走</span></span><br><span class="line">            nturn = turn == <span class="number">1</span> <span class="keyword">and</span> <span class="number">2</span> <span class="keyword">or</span> <span class="number">1</span></span><br><span class="line">            <span class="comment"># 深度优先搜索，返回评分，走的行和列</span></span><br><span class="line">            score = -self.__search(nturn, depth-<span class="number">1</span>, -beta, -alpha)</span><br><span class="line">            <span class="comment"># 棋盘上清除当前走法</span></span><br><span class="line">            self.board[row][col] = <span class="number">0</span></span><br><span class="line">           </span><br><span class="line">            <span class="comment"># 计算最好分值的走法</span></span><br><span class="line">            <span class="comment"># alpha/beta剪枝</span></span><br><span class="line">            <span class="keyword">if</span> score &gt; alpha:</span><br><span class="line">                alpha = score</span><br><span class="line">                bestmove = (row, col)</span><br><span class="line">                <span class="keyword">if</span> alpha &gt;= beta:</span><br><span class="line">                    <span class="keyword">break</span></span><br><span class="line">               </span><br><span class="line">        <span class="comment"># 如果是第一层，记录最好的走法</span></span><br><span class="line">        <span class="keyword">if</span> depth == self.maxdepth <span class="keyword">and</span> bestmove:</span><br><span class="line">            self.bestmove = bestmove</span><br><span class="line">           </span><br><span class="line">        <span class="comment"># 返回当前最好分数，及对应走法</span></span><br><span class="line">        <span class="keyword">return</span> alpha</span><br></pre></td></tr></table></figure>
<p>这就是整个算法的核心了。首先如果深度为0了，或游戏有了输赢了，就结束搜索，调用棋盘评分函数得到当前的棋盘评分，具体评分方法先跳过，后面再研究。<br>如果既没有结束也没有到最底层，就调用另一个函数genmove产生走法。对于每一个走法，包含了局面评分，位置的坐标信息。对于每一个走法，先在棋盘上标注该位置，然后轮到对手走了，再递归调用:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">score = -self.__search(nturn, depth-<span class="number">1</span>, -beta, -alpha)</span><br></pre></td></tr></table></figure>
<p>之后再恢复调用之前的棋盘状态。<br>之后计算最好分值的走法，即所谓的Alpha_Beta剪枝。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 计算最好分值的走法</span></span><br><span class="line"><span class="comment"># alpha/beta剪枝</span></span><br><span class="line"><span class="keyword">if</span> score &gt; alpha:</span><br><span class="line">    alpha = score</span><br><span class="line">    bestmove = (row, col)</span><br><span class="line">    <span class="keyword">if</span> alpha &gt;= beta:</span><br><span class="line">        <span class="keyword">break</span></span><br></pre></td></tr></table></figure>
<p>这段是我比较疑惑的地方，再找资料看看。<br>最后，如果搜索到最大层数了，记录最大分值的走法，并返回分值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 如果是第一层，记录最好的走法</span></span><br><span class="line"><span class="keyword">if</span> depth == self.maxdepth <span class="keyword">and</span> bestmove:</span><br><span class="line">    self.bestmove = bestmove</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 返回当前最好分数，及对应走法</span></span><br><span class="line"><span class="keyword">return</span> alpha</span><br></pre></td></tr></table></figure>
<p>下面具体看一下Alpha_Beta剪枝过程。参考了上面的<a target="_blank" rel="noopener" href="https://github.com/lihongxun945/myblog/labels/%E4%BA%94%E5%AD%90%E6%A3%8BAI%E6%95%99%E7%A8%8B%E7%AC%AC%E4%BA%8C%E7%89%88">那个教程</a><br>还有<a target="_blank" rel="noopener" href="https://www.xqbase.com/computer/search_alphabeta.htm">这篇</a><br>博弈树某一层是游戏一方的所有走法，下一层是另一方针对这些走法相应的所有走法，以此类推。每增加一层即代表增加一步走法。可以用递归来遍历整棵树。<br>选择分支的方法，电脑(己方)走棋的层称为MAX层，需要选分值最高的节点。人(对方)走棋的层称为MIN层，选分值最低的节点。这就是极大值极小值搜索。每个节点的分数由子节点决定，因此要进行深度优先搜索。可以把对方的分数变成负的，就能够统一完成递归过程。即负极大值搜索。层数最好是偶数。<br>Alpha_Beta剪枝算法是一种安全的剪枝策略，即不会对棋力产生任何负面影响。其原理是，明显对自己不利的节点，就不用考虑了。这个方法是建立在一个思想上的，如果你已经有一个不太坏的选择了，那么当你要作别的选择并知道它不会更好时，你没有必要确切地知道它有多坏。有了最好的选择，任何不比它更好的选择就是足够坏的，因此你可以撇开它而不需要完全了解它。只要你能证明它不比最好的选择更好，你就可以完全抛弃它。<br>在MAX层，下一层会产生比最大值小的节点就可以删去。在MIN层，下一个节点的下一层产生的值比最小值还大，可删去该节点。<br>Alpha和Beta分别指MAX和MIN节点。删节点是删本层节点的子节点。<br>具体做法有点理解了，再来看那段代码:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> score &gt; alpha:</span><br><span class="line">    alpha = score</span><br><span class="line">    bestmove = (row, col)</span><br></pre></td></tr></table></figure>
<p>这应该就是alpha剪枝，即当前节点为最大分值节点时，该位置即为候选节点。<br>而</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> alpha &gt;= beta:</span><br><span class="line">    <span class="keyword">break</span></span><br></pre></td></tr></table></figure>
<p>则为beta剪枝，即当beta节点为最小节点时，舍弃其后的节点。<br>再来看生成走法的程序:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 产生当前棋局的走法</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">genmove</span>(<span class="params">self, turn</span>):</span></span><br><span class="line">        moves = []</span><br><span class="line">        board = self.board</span><br><span class="line">        POSES = self.evaluator.POS</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(self.row):</span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(self.col):</span><br><span class="line">                <span class="keyword">if</span> board[i][j] == <span class="number">0</span>:</span><br><span class="line">                    score = POSES[i][j]</span><br><span class="line">                    moves.append((score, i, j))</span><br><span class="line">        moves.sort()</span><br><span class="line">        moves.reverse()</span><br><span class="line">        <span class="keyword">return</span> moves</span><br></pre></td></tr></table></figure>
<p>就是对棋盘上所有空的位置进行遍历，然后按其分数进行排序，从分值最大的节点进行搜索。这里的排序和逆序，是使得走法更加有序，便于后续的Alpha_Beta剪枝过程。<br>至于棋盘的评分函数，就是根据棋子落到某位置后能形成的状态，如二连，三连，四连，五连，活三，活四等情况，分别赋予一个分值，再分横，竖，左斜，右斜四个方向来算，最后的分值总额就是棋盘上这个位置的分值。最后棋盘上每个点的分值总和就是该局面的分值。双方的分值之差就是某一方的分值。具体过程比较繁琐，就不赘述了，可以看github上的源代码。<br>下面再尝试一下用不同深度的博弈树算法进行比较。<br>这个就比之前的算法慢多了。用最浅的深度1来测试，在我手机上大约6秒完成一局。提高深度到2，棋局的时间就会长很多。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/08.jpg"></p>
<p>果然差不多。把算法二的深度改成2，再试一次。放到服务器上去跑吧。</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/09.jpg"><br>跑20次，用了一小时三十九分钟。还是搜索深的胜率要高一点。这太慢了，才两层。试了一次3层的，一个多小时没下完一盘。超出忍耐极限了。优化一下?<br>参考了<a target="_blank" rel="noopener" href="https://kimlongli.github.io/2016/12/14/%E5%A6%82%E4%BD%95%E8%AE%BE%E8%AE%A1%E4%B8%80%E4%B8%AA%E8%BF%98%E5%8F%AF%E4%BB%A5%E7%9A%84%E4%BA%94%E5%AD%90%E6%A3%8BAI/">一些资料</a><br>先减少步数?输出了一下，开局时每次走棋产生的可能走法有220多种，减到10看看。即仅用前10个走法进行搜索。程序立马快了很多，进行4层搜索时，几秒钟走一步。<br>2层和4层深度pk一下:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/10.jpg"></p>
<p>17分钟，胜率46%:54%。<br>再加一下，2层和6层，时间又变得很长，大概三分钟左右下一盘。停了。<br>再试一下2层和5层<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/11.jpg"></p>
<p>100盘下了近6个小时，可2层的胜率还比5层的高……<br>比较2层和4层吧，时间还可以接受。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/12.jpg"></p>
<p>但是发现一个bug，算法会对自己或对方已经四连的情况视而不见。多纳入一些走法，前20个试试。好一点，还是有视而不见的情况，再加10个。还是不行，最后放弃这个优化，选择搜索棋盘上所有空的位置，然后再加上对周围11*11个位置都没落子的位置不搜索，终于正常了。但是搜索层数只能局限于2层了，再深时间就太长了。先到这里吧，下面终于进入本文正题:强化学习了。<br>先看一篇介绍AlphaGo的<a target="_blank" rel="noopener" href="https://blog.csdn.net/songrotek/article/details/51065143">文章</a><br>有详细的网络结构。但是貌似还用了一些棋谱数据。后来的Alpha Zero更牛，自己跟自己下就行了。就实现这个吧。<br>背后的思想是蒙特卡洛树搜索，先看一篇介绍这个的<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/34950988">文章</a>。<br>它是完美信息博弈场景中进行决策的一项通用技术。其主要目的是“给出一个‘游戏状态’并选择‘胜率最高’的下一步”。<br>博弈树是一种树结构，其中每一个节点表征博弈的确定状态。从一个节点向其子节点的转换被称为一个行动（move）。节点的子节点数目被称为分支因子（branching factor）。树的根节点表征博弈的初始状态。我们还区分了博弈树的端节点（terminal nodes），即没有子节点的节点，表示博弈无法再继续进行。端节点的状态可以被评估，并总结博弈的结果。传统的搜索方法是最大值最小值方法，以及对其的优化Alpha_Beta剪枝。<br>蒙特卡洛树搜索会多次模拟博弈，并尝试根据模拟结果预测最优的移动方案。<br>如果某个节点作为初始节点模拟过至少一次，它就可以被视为已访问节点。反向传播是从子节点(模拟开始的节点)遍历回根节点，其路径上每个节点都被计算/更新。节点的统计数据包括总模拟奖励和总访问次数。<br>根据UTC函数的值来选择要访问的节点。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/13.jpg"></p>
<p>该函数为节点v的子节点vi定义，第一项是节点vi的模拟胜率。第二项是探索组件，用于支持未被探索的节点。当资源(时间/算力)限制达到时即停止搜索，选择访问频率最高的节点。<br>接下来来看Alpha Zero的<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/32952677">原理</a><br>与Alpha go相比，最大的优点是不需要预设知识。<br>蒙特卡洛树搜索算法因为是直接模拟到游戏终局，所以这种算法更加的准确，而且并不需要一个明确的“估值函数”，你只需要实现游戏机制就足够了。而且，蒙特卡洛算法，可以随时终止，根据其训练的时间给予近似的最优结果。<br>在Alpha Zero中，除了游戏规则，没有任何背景知识，只使用一个神经网络。以棋盘为输入，以下一步各下法的概率和胜率为输出，包含多个卷积层和全连接层。其核心思想是:MCTS生成的对弈可以作为神经网络的训练数据。<br>下面还是把代码撸起来吧，主要参考这两篇文章:<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/32089487">1</a><br><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/59567014">2</a><br>由于算力的限制，这些文章都把棋盘大小设为8×8，为了一致，我把之前的程序也改成一样大小的棋盘。<br>主要照第一篇文章的代码来写。<br>先创建蒙特卡洛搜索树(MCTS)<br>基本照人家的写，为了匹配之前自己的程序，修改了很多。方法是先跑起来，然后连上自己的程序，运行，报错差什么就加什么，终于跑通了。具体实现在mcts.py里。先跟自己下一盘:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/14.jpg"></p>
<p>棋力好像不咋滴。再跟博弈树算法对几局看看。<img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/15.jpg"></p>
<p>还是能对上一阵的。<br>进行100次<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/16.jpg"></p>
<p>搜索树碾压式的赢了。<br>再试一下5000次，用了近三个小时，还是输了。<br>但是蒙特卡罗树搜索的优点是，不用再人工定死棋盘评估方法了。下面就开始进行本文的核心部分:强化学习吧。<br>首先定义强化学习用的蒙特卡罗树搜索，树的节点和搜索树的定义都跟之前的一样，直接import。只是player类里获得走法的函数有点不一样。增加了随机噪音。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_action</span>(<span class="params">self, board</span>):</span></span><br><span class="line">    sensible_moves = board.availables</span><br><span class="line">    move_probs = np.zeros(board.width*board.height)</span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">len</span>(sensible_moves) &gt; <span class="number">0</span>:</span><br><span class="line">        move = self.mcts.get_move(board, temp)</span><br><span class="line">        move_probs[<span class="built_in">list</span>(acts)] = probs</span><br><span class="line">        <span class="keyword">if</span> self._is_selfplay:</span><br><span class="line">            <span class="comment"># 增加狄利克雷分布噪音，自己训练需要</span></span><br><span class="line">            move = np.random.choice(acts, p=<span class="number">0.75</span>*probs + <span class="number">0.25</span>*np.random.dirichlet(<span class="number">0.3</span>*np.ones(<span class="built_in">len</span>(probs))))</span><br><span class="line">            <span class="comment"># 更新根节点</span></span><br><span class="line">            self.mcts.update_with_move(move)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 默认参数temp = 1e-3，近似等于选择概率最高的叶子节点</span></span><br><span class="line">            move = np.random.choice(acts, p=probs)</span><br><span class="line">            self.mcts.update_with_move(-<span class="number">1</span>)</span><br><span class="line">           </span><br><span class="line">        <span class="keyword">if</span> return_prob:</span><br><span class="line">            <span class="keyword">return</span> move, move_probs</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> move</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        print(<span class="string">&quot;棋盘满了&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>下面定义策略值网络。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 策略神经网络</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Net</span>(<span class="params">nn.Module</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, board_width, board_height</span>):</span></span><br><span class="line">        <span class="built_in">super</span>(Net, self).__init__()</span><br><span class="line">        </span><br><span class="line">        self.board_width = board_width</span><br><span class="line">        self.board_height = board_height</span><br><span class="line">        <span class="comment"># 普通层</span></span><br><span class="line">        self.conv1 = nn.Conv2d(<span class="number">4</span>, <span class="number">32</span>, kernel_size=<span class="number">3</span>, padding=<span class="number">1</span>)</span><br><span class="line">        self.conv2 = nn.Conv2d(<span class="number">32</span>, <span class="number">64</span>, kernel_size=<span class="number">3</span>, padding=<span class="number">1</span>)</span><br><span class="line">        self.conv3 = nn.Conv2d(<span class="number">64</span>, <span class="number">128</span>, kernel_size=<span class="number">3</span>, padding=<span class="number">1</span>)</span><br><span class="line">        <span class="comment"># 行动策略层</span></span><br><span class="line">        self.act_conv1 = nn.Conv2d(<span class="number">128</span>, <span class="number">4</span>, kernel_size=<span class="number">1</span>)</span><br><span class="line">        self.act_fc1 = nn.Linear(<span class="number">4</span>*board_width*board_height, board_width*board_height)</span><br><span class="line">        <span class="comment"># 状态值层</span></span><br><span class="line">        self.val_conv1 = nn.Conv2d(<span class="number">128</span>, <span class="number">2</span>, kernel_size=<span class="number">1</span>)</span><br><span class="line">        self.val_fc1 = nn.Linear(<span class="number">2</span>*board_width*board_height, <span class="number">64</span>)</span><br><span class="line">        self.val_fc2 = nn.Linear(<span class="number">64</span>, <span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<p>完全照人家的代码写的。还有策略值网络PolicyValueNet实现了训练过程，保存模型等过程。在policy_value_net.py里。<br>最后进行训练过程，在RLtrain.py里。<br>训练的流程，在run成员函数里。<br>先指定每次训练自己跟自己对弈的次数。<br>然后电脑自己跟自己打(collect_selfplay_data)，在里面调用自我对弈程序，取得每种走法的获胜概率值。然后调用get_equi_data扩增数据。主要是使用对数据进行旋转和翻转的方法，使数据规模扩大四倍。<br>获取数据后，在主函数里调用policy_update计算策略的损失函数，主要为调用策略值网络里的训练步骤进行若干次迭代(就是神经网络的前向传播，反向传播过程)，然后调整学习率等。<br>间隔一定次数，就用纯蒙特卡罗树搜索算法作为基准对强化学习模型进行评估，如果结果比之前的结果好，就保存当前模型。我又画了一下各次训练的损失函数值。<br>训练程序放到服务器上跑，跑了十多个小时，100次。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/17.jpg"></p>
<p>下面再实现用该模型来对弈。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/18.jpg"></p>
<p>结果，棋力很差……<br>跟博弈树算法PK一下:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/19.jpg"></p>
<p>显然不是对手。对战100次看看<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/20.jpg"></p>
<p>98:2，胜率那么低……但起码不是100:0，说明不是完全随机下的，还是有点“智能”在里面的。把每次搜索次数增加到1000次，再试试。训练时间大幅延长了，训练10次，花了30000多秒。再对战一下看看。<br>结果类似，99:1。把训练次数增加100倍到1000次看看。在我的破服务器上要跑好几天的。<br>租GPU试试？<br>租GPU跑了50次，到50次时出现迭代次数超出限制的错误停止了。用训练的模型对弈一下看看，注意要在GPU环境下，如果在CPU环境下就报错。不知道为啥。棋力还是很差。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/73/21.jpg"></p>
<p>跟博弈树算法对弈100次看看，结果，99:1。把mcts搜索次数增加到1000次看看。结果还是99:1……<br>换作者训练好的模型看看。可能作者用的python2的缘故，加载出错。还是想想调参吧。要调参先要理解原理，读读论文吧：<br>Mastering the game of Go with deep neural networks and tree search<br>译文:<a target="_blank" rel="noopener" href="https://blog.csdn.net/u013390476/article/details/50925347">1</a><br><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/20607684">2</a><br>通过一个估值网络“value network”来评估局面，通过一个策略网络“polic network”来产生下法，采用了以人类选手作为训练特征的有监督学习和以算法自我对弈进行的强化学习。采用蒙特卡罗树搜索来进行随机的棋局对弈。用一个新的搜索算法结合了蒙特卡洛模拟和策略网络。第一次计算机在全尺寸围棋游戏中战胜了人类专业选手。<br>所有完美信息博弈都有一个最优值函数，可以通过对搜索树进行b*d(b为可能的走法数量，d为搜索深度)次递归搜索而解决。对围棋来说，这个数值十分巨大，超过了算力可能。可以通过最大最小值算法进行优化，降低计算量。但对围棋来说，剩下的可能性仍然很巨大。另外可以通过随机搜索部分可能的走法降低搜索的广度。Alphago采用一个监督学习的神经网络，用人类专业棋手的棋谱来训练一个分类器，然后用训练的结果初始化强化学习策略网络，后者以自我对弈的方式进行训练，以获胜概率最大化为目标，并用回归的形式得到局面估值。Alphago与监督学习策略网络对战，胜率为80%。与之前最好的围棋软件Pachi对战，胜率85%。最终使用了40个搜索线程，48个CPU和8个GPU。还有分布式版本，使用了1202个CPU和176个GPU。</p>
<p>还有AlphaZero的论文Mastering the game of Go without human knowledge<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/sinat_31428707/article/details/82218575">译文</a><br>与AlphaGo相比，AlphaZero最大的特点是不再需要人类的知识，只进行强化学习即可。<br>专业知识通常是昂贵的，不可靠的，甚至不可获得的。即便可以获得可靠的数据，它们也将成为系统的上限。AlphaZero的另一个特点是其只使用棋盘上黑白棋子的位置作为输入特征，另外，它只使用单一的神经网络。最后，它使用更简单的树搜索。模型的输出为走法概率和一个值。</p>
<p>总结一下强化学习的五子棋棋力不高的原因，首先可能是训练时模拟的方法不行，是用的蒙特卡洛树搜索算法，这个也许用在围棋上挺适合的，但是跟博弈树算法对打时棋力很差。第二，可能也是最重要的原因，训练的次数太少，还不够。<br>接下来打算看看书，详细了解一下强化学习背后的原理。<br>程序<a target="_blank" rel="noopener" href="https://github.com/zwdnet/FiveZiQi">代码</a></p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/%E5%BC%BA%E5%8C%96%E5%AD%A6%E4%B9%A0/" rel="tag"># 强化学习</a>
          
            <a href="/tags/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/" rel="tag"># 人工智能</a>
          
            <a href="/tags/AI/" rel="tag"># AI</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/03/11/%E5%AF%8C%E8%A1%80%E5%B0%8F%E6%9D%BF%E7%BA%A4%E7%BB%B4%E8%9B%8B%E7%99%BD%E5%9C%A8%E6%8B%94%E7%89%99%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8/" rel="next" title="富血小板纤维蛋白在拔牙中的应用">
                <i class="fa fa-chevron-left"></i> 富血小板纤维蛋白在拔牙中的应用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/03/16/%E5%AD%A6%E4%B9%A0%E5%A4%B4%E5%BD%B1%E6%B5%8B%E9%87%8F1%E2%80%94%E2%80%94%E8%A7%A3%E5%89%96%E7%BB%93%E6%9E%84%E6%8F%8F%E8%AE%B0%E5%9B%BE/" rel="prev" title="学习头影测量1——解剖结构描记图">
                学习头影测量1——解剖结构描记图 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
